<template>
  <div v-loading="pageLoading">
    <!-- 申请信息 -->
    <div class="padding20 whiteBg br-8">
      <div class="form_title">申请信息</div>
      <el-row class="form_row">
        <el-col :span="8">
          <div class="form_item">
            <span class="form_label">编号：</span>
            <span class="form_value">{{ formData.code || '--' }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="form_item">
            <span class="form_label">登记人：</span>
            <span class="form_value">{{ currentUser || '--' }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="form_item">
            <span class="form_label">申请日期：</span>
            <span class="form_value">{{ currentDate }}</span>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 基本信息 -->
    <div class="m-t-16 whiteBg padding20 br-8">
      <div class="form_title">基本信息</div>
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="form_container"
        :disabled="isViewMode"
        :validate-on-rule-change="false"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="类型" prop="level">
              <el-select
                v-model="formData.level"
                placeholder="请选择"
                style="width: 100%"
                clearable
                :disabled="isEditMode"
              >
                <el-option
                  v-for="item in levelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        <el-col :span="12">
          <el-form-item label="上级分类" prop="parentCategoryCode">
            <el-select
              v-model="formData.parentCategoryCode"
              placeholder="请选择"
              style="width: 100%"
              filterable
              remote
              reserve-keyword
              :remote-method="handleParentCategoryRemoteSearch"
              :loading="parentCategoryLoading"
              clearable
              :disabled="!showParentCategoryField || isViewMode"
              @visible-change="handleParentCategoryVisibleChange"
            >
              <el-option
                v-for="item in parentCategoryOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              >
                <span class="select-option-code">{{ item.code }}</span>
                <span class="select-option-name">{{ item.name }}</span>
              </el-option>
              <template #footer>
                <SelectPagination
                  v-if="showParentCategoryPagination && !isViewMode"
                  :page-total="parentCategoryPageTotal"
                  :page-per-num="parentCategoryPageSize"
                  :current-page="parentCategoryPageNo"
                  @handleSizeChange="handleParentCategorySizeChange"
                  @handleCurrentChange="handleParentCategoryPageChange"
                />
              </template>
            </el-select>
          </el-form-item>
        </el-col>
        
          <el-col :span="12">
            <el-form-item label="分类名称" prop="categoryName">
              <el-input
                v-model="formData.categoryName"
                placeholder="请输入"
                maxlength="20"
                @input="handleCategoryNameInput"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 商品属性 -->
    <div class="m-t-16 whiteBg padding20 br-8" v-if="showProductAttributeBlock">
      <div class="form_title">商品属性</div>
      <div
        v-for="section in PRODUCT_SECTIONS"
        :key="section.key"
        class="product_section"
      >
        <div class="section_header sub_section_header">
          <div class="sub_title">{{ section.label }}</div>
          <el-button
            type="primary"
            @click="handleAddProductAttr(section.key)"
            v-if="!isViewMode"
          >
            添加
          </el-button>
        </div>

        <el-table
          class="list_table table-scroll"
          :data="productAttributeSections[section.key]"
          border
          style="width: 100%"
          :header-cell-class-name="handleHeaderCellClass"
          :empty-text="`暂无${section.label}`"
        >
          <el-table-column label="序号" width="70" align="center">
            <template #default="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column label="属性名称" min-width="200">
            <template #default="scope">
              <!-- 详情模式下直接展示接口返回的 propertyName，避免依赖下拉 options -->
              <span v-if="isViewMode">{{ scope.row.propertyName || '--' }}</span>
              <el-select
                v-else
                v-model="scope.row.propertyCode"
                placeholder="请选择"
                filterable
                clearable
                style="width: 100%"
                :disabled="isViewMode"
                @change="handleProductPropertyChange(section.key, scope.row)"
              >
                <el-option
                  v-for="item in productPropertyOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                >
                  <span class="select-option-code">{{ item.code }}</span>
                  <span class="select-option-name">{{ item.name }}</span>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="输入类型" width="140">
            <template #default="scope">
              <el-select
                v-model="scope.row.inputType"
                placeholder="请选择"
                clearable
                style="width: 100%"
                :disabled="isViewMode"
                @change="handleInputTypeChange(scope.row)"
              >
                <el-option
                  v-for="item in inputTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="属性值" min-width="220">
            <template #default="scope">
              <el-select
                v-model="scope.row.propertyValueCodes"
                placeholder="请选择"
                filterable
                multiple
                collapse-tags
                collapse-tags-tooltip
                clearable
                style="width: 100%"
                :disabled="isViewMode || scope.row.inputType === '2'"
              >
                <el-option
                  v-for="item in scope.row.valueOptions"
                  :key="item.value"
                  :label="getPropertyValueName(item.label)"
                  :value="item.value"
                >
                  <span class="select-option-code">{{ getPropertyValueCode(item.label) }}</span>
                  <span class="select-option-name">{{ getPropertyValueName(item.label) }}</span>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="是否必填" width="120">
            <template #default="scope">
              <el-select
                v-model="scope.row.requiredFlag"
                placeholder="请选择"
                clearable
                style="width: 100%"
                :disabled="isViewMode"
              >
                <el-option
                  v-for="item in yesNoOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="是否用于商品名称展示" width="200">
            <template #default="scope">
              <el-select
                v-model="scope.row.showInName"
                placeholder="请选择"
                clearable
                style="width: 100%"
                :disabled="isViewMode"
              >
                <el-option
                  v-for="item in yesNoOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="是否适用于易购筛选" width="180">
            <template #default="scope">
              <el-select
                v-model="scope.row.useForFilter"
                placeholder="请选择"
                clearable
                style="width: 100%"
                :disabled="isViewMode"
              >
                <el-option
                  v-for="item in yesNoOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="是否允许供应商修改" width="180">
            <template #default="scope">
              <el-select
                v-model="scope.row.allowSupplierEdit"
                placeholder="请选择"
                clearable
                style="width: 100%"
                :disabled="isViewMode"
              >
                <el-option
                  v-for="item in yesNoOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="是否在商品详情页展示" width="200">
            <template #default="scope">
              <el-select
                v-model="scope.row.showInDetail"
                placeholder="请选择"
                clearable
                style="width: 100%"
                :disabled="isViewMode"
              >
                <el-option
                  v-for="item in yesNoOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="数值输入提示" min-width="200">
            <template #default="scope">
              <el-input
                v-model="scope.row.valueHint"
                placeholder="请输入"
                maxlength="20"
                :disabled="isViewMode"
              >
              </el-input>
            </template>
          </el-table-column>
          <el-table-column
            v-if="!isViewMode"
            label="操作"
            width="200"
            align="center"
            fixed="right"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="handleMoveProductAttr(section.key, scope.$index, 'up')"
                :disabled="scope.$index === 0"
              >
                上移
              </el-button>
              <el-button
                link
                type="primary"
                @click="handleMoveProductAttr(section.key, scope.$index, 'down')"
                :disabled="scope.$index === productAttributeSections[section.key].length - 1"
              >
                下移
              </el-button>
              <el-button
                link
                type="primary"
                @click="handleRemoveProductAttr(section.key, scope.$index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分类属性 -->
    <div class="m-t-16 whiteBg padding20 br-8">
      <div class="form_title">
        <div class="">分类属性</div>
      </div>
      <div class="section_header sub_section_header">
        <el-button v-if="!isViewMode" type="primary" @click="handleAddCategoryAttr">
          添加
        </el-button>
      </div>

      <el-table
        class="list_table table-scroll"
        :data="categoryAttributes"
        border
        style="width: 100%"
        :header-cell-class-name="handleHeaderCellClass"
        empty-text="暂无分类属性"
      >
        <el-table-column label="序号" width="70" align="center">
          <template #default="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="属性类别" min-width="180">
          <template #default="scope">
            <el-select
              v-model="scope.row.attributeCategoryCode"
              placeholder="请选择"
              filterable
              clearable
              style="width: 100%"
              :disabled="isViewMode"
              @change="handleCategoryPropertyCategoryChange(scope.row)"
            >
              <el-option
                v-for="item in scope.row.propertyCategoryList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              >
                <span class="select-option-code">{{ item.code }}</span>
                <span class="select-option-name">{{ item.name }}</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="属性名称" min-width="220">
          <template #default="scope">
            <el-select
              v-model="scope.row.propertyCode"
              placeholder="请选择"
              filterable
              clearable
              style="width: 100%"
              :disabled="isViewMode || !scope.row.attributeCategoryCode"
              @change="handleCategoryPropertyNameChange(scope.row)"
            >
              <el-option
                v-for="item in scope.row.propertyCategoryOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              >
                <span class="select-option-code">{{ item.code }}</span>
                <span class="select-option-name">{{ item.name }}</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="属性值" min-width="200">
          <template #default="scope">
            <el-select
              v-model="scope.row.propertyValueCode"
              placeholder="请选择"
              filterable
              clearable
              style="width: 100%"
              :disabled="isViewMode || !scope.row.propertyCode"
            >
              <el-option
                v-for="item in scope.row.propertyValueOptions"
                :key="item.value"
                :label="getPropertyValueName(item.label)"
                :value="item.value"
              >
                <span class="select-option-code">{{ getPropertyValueCode(item.label) }}</span>
                <span class="select-option-name">{{ getPropertyValueName(item.label) }}</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          v-if="!isViewMode"
          label="操作"
          width="200"
          align="center"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleMoveCategoryAttr(scope.$index, 'up')"
              :disabled="scope.$index === 0"
            >
              上移
            </el-button>
            <el-button
              link
              type="primary"
              @click="handleMoveCategoryAttr(scope.$index, 'down')"
              :disabled="scope.$index === categoryAttributes.length - 1"
            >
              下移
            </el-button>
            <el-button
              link
              type="primary"
              @click="handleRemoveCategoryAttr(scope.$index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="m-t-24 align-right">
      <el-button @click="handleCancel">取消</el-button>
      <el-button
        v-if="!isViewMode"
        type="primary"
        :loading="submitLoading"
        @click="handleSubmit"
      >
        提交
      </el-button>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  computed,
  onMounted,
  watch,
} from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { userInfoStore,pageTabsStore } from '@/store/index';
import { categoryAPI } from '@/api/categoryManagement';
import { attributeAPI } from '@/api/attributeManagement';
import SelectPagination from '@/components/common/selectPagination/index.vue';
import commonJs from '@/utils/common.js';

const handelPageTab = pageTabsStore();
const DEFAULT_PARENT_QUERY_LEVEL = 2;
const PRODUCT_SECTIONS = [
  { key: 'material', label: '物料属性' },
  { key: 'goods', label: '商品属性' },
  { key: 'display', label: '其他展示属性' },
];

const levelOptions = [
  { label: '大类', value: '1' },
  { label: '中类', value: '2' },
  { label: '品类', value: '3' },
];

const inputTypeOptions = [
  { label: '选择', value: '1' },
  { label: '输入', value: '2' },
];

const yesNoOptions = [
  { label: '是', value: '1' },
  { label: '否', value: '0' },
];

const router = useRouter();
const route = useRoute();
const userStore = userInfoStore();

const formRef = ref(null);
const pageLoading = ref(false);
const submitLoading = ref(false);
const currentUser = ref('系统用户');

// 申请日期：新增/编辑使用当前日期，详情使用接口返回的 updateTime（仅显示年月日）
const detailUpdateTime = ref('');

const currentDate = computed(() => {
  if (isViewMode.value && detailUpdateTime.value) {
    // 后端返回格式类似：2025-11-24 09:41:18，只取前 10 位日期
    return String(detailUpdateTime.value).slice(0, 10);
  }
  const now = new Date();
  return now.toISOString().split('T')[0];
});

const formData = reactive({
  code: '--',
  categoryId: '', // 分类主键ID
  level: '',
  parentCategoryCode: '',
  categoryName: '',
  categoryTypeCode: '', // 从路由获取的分类类型code
});

const parentCategoryOptions = ref([]);

// 上级分类分页与搜索状态
const parentCategoryPageNo = ref(1);
const parentCategoryPageSize = ref(10);
const parentCategoryPageTotal = ref(0);
const parentCategorySearchKeyword = ref('');
const parentCategoryLoading = ref(false);
// 是否已经为当前 level 加载过上级分类列表（用于控制首次自动加载）
const hasLoadedParentCategories = ref(false);
// 当前已选中的上级分类（用于编辑/详情回显时保证选中项始终在第一页 options 中）
const selectedParentCategory = ref(null);

const allPropertyList = ref([]); // 所有属性列表（按controlCategoryType分类）
const categoryAttributes = ref([]);
const productPropertyOptions = ref([]); // 商品属性名称选项列表
const productAttributeSections = reactive({
  material: [],
  goods: [],
  display: [],
});

// 属性三级联动缓存
const propertyCategoryCache = new Map(); // controlCategoryType -> 属性类别列表
const propertyNameCache = new Map(); // propertyTypeCode -> 属性名称列表
const propertyValueCache = new Map(); // propertyCode -> 属性值列表

const mode = computed(() => {
  if (route.name === 'categoryManagementDetail' || route.query.mode === 'view') {
    return 'view';
  }
  if (route.name === 'categoryManagementEdit') return 'edit';
  return route.query.code ? 'edit' : 'add';
});
const isEditMode = computed(() => mode.value === 'edit' || mode.value === 'view');
const isViewMode = computed(() => mode.value === 'view');
const showParentCategoryField = computed(
  () => formData.level && formData.level !== '1'
);
// 上级分类是否需要显示分页（总数大于单页数量时展示）
const showParentCategoryPagination = computed(
  () => parentCategoryPageTotal.value > parentCategoryPageSize.value
);
const showProductAttributeBlock = computed(() => formData.level === '3');

const formRules = computed(() => {
  const rules = {
    level: [
      { required: true, message: '【类型不允许为空。】', trigger: 'change' },
    ],
    categoryName: [
      { required: true, message: '【分类名称不允许为空。】', trigger: 'blur' },
      {
        validator: (_, value, callback) => {
          if (value && value.length > 20) {
            callback(new Error('分类名称超长，请重新输入。'));
            return;
          }
          callback();
        },
        trigger: 'blur',
      },
    ],
  };

  if (showParentCategoryField.value) {
    rules.parentCategoryCode = [
      { required: true, message: '【上级分类不允许为空。】', trigger: 'change' },
    ];
  }

  return rules;
});

// 获取指定controlCategoryType下的属性类别（第一级）
const getPropertyCategoriesByType = async (level) => {
  if (!level) return [];

  if (propertyCategoryCache.has(level)) {
    return propertyCategoryCache.get(level);
  }

  try {
    const params = {
      controlCategoryType: level, // 直接使用 1,2,3,4
    };
    const res = await attributeAPI.getPropertyCategories(params, true);
    const rows = res.data || [];

    // 映射属性类别列表
    const categories = rows.map(item => ({
      code: item.code,              // P101, P102 等
      name: item.description,        // 财务属性、采购属性等
      propertyCode: item.code,       // 用于查询属性名称
    }));

    propertyCategoryCache.set(level, categories);
    return categories;
  } catch (error) {
    console.error('获取属性类别失败:', error);
    return [];
  }
};

// 获取指定属性类别下的属性名称列表（第二级）
const getPropertyNamesByCategory = async (level, propertyTypeCode) => {
  if (!level || !propertyTypeCode) return [];

  const cacheKey = `${level}_${propertyTypeCode}`;

  if (propertyNameCache.has(cacheKey)) {
    return propertyNameCache.get(cacheKey);
  }

  try {
    const params = {
      propertyType: propertyTypeCode, // 选中的属性类别code（如P101）
      controlCategoryType: level, // 直接使用 1,2,3,4
    };
    const res = await attributeAPI.getPropertyHierarchy(params, true);
    const rows = res.data || [];

    const properties = rows.map(item => ({
      code: item.propertyCode,
      name: item.propertyName,
      propertyCode: item.propertyCode,
      propertyValues: item.propertyValues || [], // 属性值列表
    }));

    propertyNameCache.set(cacheKey, properties);
    return properties;
  } catch (error) {
    console.error('获取属性名称列表失败:', error);
    return [];
  }
};

// 获取属性值列表（第三级）- 从属性名称数据中获取
const getPropertyValuesByCode = async (propertyCode) => {
  if (!propertyCode) return [];

  if (propertyValueCache.has(propertyCode)) {
    return propertyValueCache.get(propertyCode);
  }

  // 从已缓存的属性名称列表中查找
  for (const [key, properties] of propertyNameCache.entries()) {
    const property = properties.find(p => p.propertyCode === propertyCode);
    if (property && property.propertyValues) {
      const values = property.propertyValues.map((item) => ({
        label: item.valueCode
          ? `${item.valueCode} - ${item.valueName}`
          : item.valueName,
        value: item.valueCode || item.valueName,
      }));
      propertyValueCache.set(propertyCode, values);
      return values;
    }
  }

  // 如果缓存中没有，则调用详情接口获取
  try {
    const res = await attributeAPI.getPropertyDetail(propertyCode, true);
    const detail = res.data || {};
    const values = (detail.propertyValues || []).map((item) => ({
      label: item.valueCode
        ? `${item.valueCode} - ${item.valueName}`
        : item.valueName,
      value: item.valueCode || item.valueName,
    }));
    propertyValueCache.set(propertyCode, values);
    return values;
  } catch (error) {
    console.error('获取属性值失败:', error);
    return [];
  }
};

/**
 * 获取属性详情（用于商品属性，需要获取 propertyType 和 propertyTypeName）
 */
const getPropertyDetail = async (propertyCode) => {
  if (!propertyCode) return null;

  try {
    const res = await attributeAPI.getPropertyDetail(propertyCode, true);
    const detail = res.data || {};
    return {
      propertyType: detail.propertyType || '',
      propertyTypeName: detail.propertyTypeName || '',
      propertyValues: detail.propertyValues || []
    };
  } catch (error) {
    console.error('获取属性详情失败:', error);
    return null;
  }
};

/**
 * 获取商品属性名称列表(品类专用)
 * 逻辑: 先调用 SKU_Property_TYPE 获取 code 列表,拼接后调用 property/list
 */
const getProductPropertyOptions = async () => {
  try {
    // 第一步: 获取 SKU 属性类型列表
    const res1 = await attributeAPI.getSKUPropertyTypes(true);
    const rows = res1.data || [];

    if (!rows || rows.length === 0) {
      productPropertyOptions.value = [];
      return;
    }

    // 第二步: 拼接所有 code 成逗号分隔的字符串
    const propertyTypeCodes = rows.map(item => item.code).filter(Boolean).join(',');

    if (!propertyTypeCodes) {
      productPropertyOptions.value = [];
      return;
    }

    // 第三步: 使用拼接的 propertyType 参数调用 property/list
    const res2 = await attributeAPI.getPropertyList({
      propertyType: propertyTypeCodes,
      pageNo: 1,
      pageSize: 500,
      status: 1,
    }, true);
    const propertyList = res2.data || [];

    productPropertyOptions.value = propertyList.map(item => ({
      code: item.propertyCode || item.code,
      name: item.propertyName || item.name || item.description,
    }));
  } catch (error) {
    console.error('获取商品属性列表失败:', error);
    productPropertyOptions.value = [];
  }
};

const handleHeaderCellClass = () => 'header-cell';

// 从 label 中解析属性值的 code 和 name
// label 可能是 "CODE - 名称"、"CODE-名称" 或仅 "名称"
const parsePropertyValueLabel = (label) => {
  if (!label) return { code: '', name: '' };
  const str = String(label);

  // 既兼容 "CODE - 名称"，也兼容 "CODE-名称" 这种没有空格的格式
  const hyphenIndex = str.indexOf('-');
  if (hyphenIndex > -1) {
    const code = str.slice(0, hyphenIndex).trim();
    const name = str.slice(hyphenIndex + 1).trim();
    return { code, name };
  }

  // 没有连字符时，整个字符串视为名称
  return { code: '', name: str.trim() };
};

const getPropertyValueCode = (label) => parsePropertyValueLabel(label).code;
const getPropertyValueName = (label) => parsePropertyValueLabel(label).name;

const handleCategoryNameInput = (val) => {
  if (val && val.length > 20) {
    formData.categoryName = val.slice(0, 20);
    ElMessage.warning('分类名称超长，请重新输入。');
  }
};

const handleAddCategoryAttr = async () => {
  const row = createCategoryAttributeRow();

  // 加载属性类别选项（第一级）
  if (formData.level) {
    const categories = await getPropertyCategoriesByType(formData.level);
    row.propertyCategoryList = categories;
  }

  categoryAttributes.value.push(row);
};

const handleRemoveCategoryAttr = async (index) => {
  const row = categoryAttributes.value[index];

  // 编辑模式且是已有关系（有 id）时，需要确认再删除
  if (isEditMode.value && row.id) {
    try {
      await ElMessageBox.confirm('确认删除该分类属性吗？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      });

      await categoryAPI.deleteCategoryPropertyRelation(row.id, true);
      ElMessage.success('删除成功');
    } catch (error) {
      if (error !== 'cancel' && error !== 'close') {
        console.error('删除关联关系失败:', error);
        ElMessage.error('删除失败');
      }
      return; // 取消或失败时不从列表中移除
    }
  }

  // 新增行或删除成功后，从列表中移除
  categoryAttributes.value.splice(index, 1);
};

// 分类属性 - 上移下移
const handleMoveCategoryAttr = (index, direction) => {
  if (direction === 'up' && index > 0) {
    // 上移：与上一项交换位置
    const temp = categoryAttributes.value[index];
    categoryAttributes.value[index] = categoryAttributes.value[index - 1];
    categoryAttributes.value[index - 1] = temp;
  } else if (direction === 'down' && index < categoryAttributes.value.length - 1) {
    // 下移：与下一项交换位置
    const temp = categoryAttributes.value[index];
    categoryAttributes.value[index] = categoryAttributes.value[index + 1];
    categoryAttributes.value[index + 1] = temp;
  }
};

// 分类属性 - 属性类别变化（第一级）
const handleCategoryPropertyCategoryChange = async (row) => {
  row.propertyCode = '';
  row.propertyValueCode = '';
  row.propertyValueOptions = [];

  if (row.attributeCategoryCode) {
    // 加载属性名称列表（第二级）
    const options = await getPropertyNamesByCategory(
      formData.level,
      row.attributeCategoryCode
    );
    row.propertyCategoryOptions = options;
  } else {
    row.propertyCategoryOptions = [];
  }
};

// 分类属性 - 属性名称变化（第二级）
const handleCategoryPropertyNameChange = async (row) => {
  row.propertyValueCode = '';

  if (row.propertyCode) {
    if (
      isDuplicateProperty(
        categoryAttributes.value,
        row.uid,
        row.propertyCode,
        'propertyCode'
      )
    ) {
      ElMessage.error('【属性已存在，请勿重复添加。】');
      row.propertyCode = '';
      return;
    }
    const options = await getPropertyValuesByCode(row.propertyCode);
    row.propertyValueOptions = options;
  } else {
    row.propertyValueOptions = [];
  }
};

// 商品属性 - 属性名称变化
const handleProductPropertyChange = async (sectionKey, row) => {
  row.propertyValueCodes = [];
  row.valueOptions = [];
  row.propertyTypeCode = '';
  row.propertyTypeName = '';

  if (row.propertyCode) {
    // 当基本信息类型为「品类」时，商品属性三个大类中属性名称整体不能重复
    if (formData.level === '3') {
      if (isDuplicateProductPropertyAcrossSections(row.uid, row.propertyCode)) {
        ElMessage.error('【属性已存在，请勿重复添加。】');
        row.propertyCode = '';
        return;
      }
    } else if (
      isDuplicateProperty(
        productAttributeSections[sectionKey],
        row.uid,
        row.propertyCode,
        'propertyCode'
      )
    ) {
      // 非品类时，保持原有「同一分组内不可重复」规则
      ElMessage.error('【属性已存在，请勿重复添加。】');
      row.propertyCode = '';
      return;
    }

    // 获取属性详情，包含 propertyType、propertyTypeName 和属性值列表
    const detail = await getPropertyDetail(row.propertyCode);
    if (detail) {
      // 保存 propertyType 和 propertyTypeName
      row.propertyTypeCode = detail.propertyType;
      row.propertyTypeName = detail.propertyTypeName;

      // 构建属性值选项
      const valueOptions = detail.propertyValues.map((item) => ({
        label: item.valueCode
          ? `${item.valueCode} - ${item.valueName}`
          : item.valueName,
        value: item.valueCode || item.valueName,
      }));
      row.valueOptions = valueOptions;
    }
  }
};

// 添加商品属性行
const handleAddProductAttr = (sectionKey) => {
  productAttributeSections[sectionKey].push(createProductAttributeRow());
};

// 删除商品属性行
const handleRemoveProductAttr = async (sectionKey, index) => {
  const row = productAttributeSections[sectionKey][index];

  // 编辑模式且是已有关系（有 id）时，需要确认再删除
  if (isEditMode.value && row.id) {
    try {
      await ElMessageBox.confirm('确认删除该商品属性吗？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      });

      await categoryAPI.deleteCategoryPropertyRelation(row.id, true);
      ElMessage.success('删除成功');
    } catch (error) {
      if (error !== 'cancel' && error !== 'close') {
        console.error('删除关联关系失败:', error);
        ElMessage.error('删除失败');
      }
      return; // 取消或失败时不从列表中移除
    }
  }

  // 新增行或删除成功后，从列表中移除
  productAttributeSections[sectionKey].splice(index, 1);
};

// 商品属性 - 上移下移
const handleMoveProductAttr = (sectionKey, index, direction) => {
  const list = productAttributeSections[sectionKey];
  if (direction === 'up' && index > 0) {
    // 上移：与上一项交换位置
    const temp = list[index];
    list[index] = list[index - 1];
    list[index - 1] = temp;
  } else if (direction === 'down' && index < list.length - 1) {
    // 下移：与下一项交换位置
    const temp = list[index];
    list[index] = list[index + 1];
    list[index + 1] = temp;
  }
};

const handleInputTypeChange = (row) => {
  if (row.inputType === '2') { // 2=输入
    row.propertyValueCodes = [];
  }
};

const clearParentCategoryValidation = () => {
  if (formRef.value && formRef.value.clearValidate) {
    formRef.value.clearValidate('parentCategoryCode');
  }
};

const handleCancel = () => {
   // 删除 store 中对应的路由标签
  handelPageTab.deleteTab(route.name);

  router.back();
};

const handleSubmit = () => {
  if (isViewMode.value) return;
  formRef.value?.validate(async (valid) => {
    if (!valid) return;
    if (!validateTableData()) return;

    const payload = buildSubmitPayload();

    submitLoading.value = true;
    try {
      if (isEditMode.value) {
        await categoryAPI.updateCategory(payload, true);
        ElMessage.success('修改成功');
      } else {
        await categoryAPI.addCategory(payload, true);
        ElMessage.success('新增成功');
      }
      handelPageTab.deleteTab(route.name);
      router.push({
        path: '/hpurchase/goodsManagement/categoryManagement',
      });
    } catch (error) {
      console.error('提交失败:', error);
      ElMessage.error('提交失败');
    } finally {
      submitLoading.value = false;
    }
  });
};

const validateTableData = () => {
  for (const row of categoryAttributes.value) {
    if (!row.attributeCategoryCode) {
      showRequiredMessage('属性类别');
      return false;
    }
    if (!row.propertyCode) {
      showRequiredMessage('属性名称');
      return false;
    }
    if (!row.propertyValueCode) {
      showRequiredMessage('属性值');
      return false;
    }
  }

  if (showProductAttributeBlock.value) {
    for (const section of PRODUCT_SECTIONS) {
      for (const row of productAttributeSections[section.key]) {
        if (!row.propertyCode) {
          showRequiredMessage('属性名称');
          return false;
        }
        if (!row.inputType) {
          showRequiredMessage('输入类型');
          return false;
        }
        if (
          row.inputType === '1' &&
          (!row.propertyValueCodes || row.propertyValueCodes.length === 0)
        ) {
          showRequiredMessage('属性值');
          return false;
        }
        if (!row.requiredFlag) {
          showRequiredMessage('是否必填');
          return false;
        }
         if (!row.showInName) {
          showRequiredMessage('是否用于商品名称展示');
          return false;
        }
        if (!row.useForFilter) {
          showRequiredMessage('是否适用于易购筛选');
          return false;
        }
        if (!row.allowSupplierEdit) {
          showRequiredMessage('是否允许供应商修改');
          return false;
        }
        if (!row.showInDetail) {
          showRequiredMessage('是否在商品详情页展示');
          return false;
        }
      }
    }
  }

  return true;
};

const showRequiredMessage = (fieldLabel) => {
  ElMessage.error(`【${fieldLabel}不允许为空。】`);
};

const buildSubmitPayload = () => {
  const categoryPropertyList = [];

  // 添加分类属性（type=4），sort 从 1 开始
  let sortForType4 = 1;
  categoryAttributes.value.forEach((attr) => {
    // 获取属性类别信息
    const propertyTypeItem = attr.propertyCategoryList?.find(
      item => item.code === attr.attributeCategoryCode
    );

    // 获取属性名称信息
    const propertyNameItem = attr.propertyCategoryOptions?.find(
      item => item.code === attr.propertyCode
    );

    // 获取属性值信息
    const propertyValueItem = attr.propertyValueOptions?.find(
      item => item.value === attr.propertyValueCode
    );

    const categoryPropertyItem = {
      sort: sortForType4++, // type=4 独立计数
      propertyTypeCode: attr.attributeCategoryCode || '',
      propertyTypeName: propertyTypeItem?.name || '',
      type: '4', // 分类属性
      propertyCode: attr.propertyCode || '',
      propertyName: propertyNameItem?.name || '',
      propertyValueList: attr.propertyValueCode ? [{
        code: attr.propertyValueCode,
        // 仅传中文名给后端，去掉 label 中的 code-
        name: getPropertyValueName(propertyValueItem?.label || '')
      }] : []
    };

    // 编辑模式下，如果有 id，添加 categoryPropertyId
    if (isEditMode.value && attr.id) {
      categoryPropertyItem.categoryPropertyId = attr.id;
    }

    categoryPropertyList.push(categoryPropertyItem);
  });

  // 添加商品属性（type=1,2,3），每个 type 的 sort 独立从 1 开始
  PRODUCT_SECTIONS.forEach((section) => {
    const typeMap = {
      material: '1',
      goods: '2',
      display: '3',
    };

    let sortForCurrentType = 1; // 每个 type 独立计数

    productAttributeSections[section.key].forEach((attr) => {
      // 构建扩展属性对象
      const extProperty = {
        inputType: attr.inputType || '1', // 直接使用值：1=选择，2=输入
        inputStatus: attr.requiredFlag === '1' ? '1' : '0',
        skuNameShowStatus: attr.showInName === '1' ? '1' : '0',
        egoFilterStatus: attr.useForFilter === '1' ? '1' : '0',
        supplierChangeStatus: attr.allowSupplierEdit === '1' ? '1' : '0',
        skuDetailShowStatus: attr.showInDetail === '1' ? '1' : '0',
        inputTips: attr.valueHint || '',
      };

      // 从选项中获取属性信息
      const propertyInfo = productPropertyOptions.value.find(
        item => item.code === attr.propertyCode
      );

      // 构建属性值列表
      const propertyValueList = (attr.propertyValueCodes || []).map(valueCode => {
        const valueInfo = attr.valueOptions?.find(v => v.value === valueCode);
        return {
          code: valueCode,
          name: valueInfo?.label?.split(' - ')[1] || valueInfo?.label || ''
        };
      });

      const productPropertyItem = {
        sort: sortForCurrentType++, // 当前 type 独立计数
        propertyTypeCode: attr.propertyTypeCode || '', // 使用保存的 propertyTypeCode
        propertyTypeName: attr.propertyTypeName || '', // 使用保存的 propertyTypeName
        type: typeMap[section.key] || '1',
        propertyCode: attr.propertyCode || '',
        propertyName: propertyInfo?.name || '',
        propertyValueList: propertyValueList,
        extProperty: extProperty
      };

      // 编辑模式下，如果有 id，添加 categoryPropertyId
      if (isEditMode.value && attr.id) {
        productPropertyItem.categoryPropertyId = attr.id;
      }

      categoryPropertyList.push(productPropertyItem);
    });
  });

  const payload = {
    categoryTypeCode: formData.categoryTypeCode, // 从路由获取的分类类型code
    categoryName: formData.categoryName?.trim(),
    parentCategoryCode: showParentCategoryField.value
      ? formData.parentCategoryCode
      : undefined,
    parentCategoryName:
      showParentCategoryField.value && formData.parentCategoryCode
        ? (selectedParentCategory.value?.name || '')
        : undefined,
    categoryPropertyList: categoryPropertyList
  };

  // 编辑模式添加额外参数
  if (isEditMode.value) {
    payload.categoryId = formData.categoryId; // 分类主键ID
    payload.categoryCode = formData.code; // 分类编码
  }

  // 删除 undefined 值
  Object.keys(payload).forEach((key) => {
    if (payload[key] === undefined) {
      delete payload[key];
    }
  });

  return payload;
};

const isDuplicateProperty = (rows, uid, value, field = 'propertyCode') =>
  rows.some((item) => item.uid !== uid && item[field] === value);

// 商品属性去重：在三个大分组（物料属性/商品属性/其他展示属性）中整体不能重复
const isDuplicateProductPropertyAcrossSections = (uid, propertyCode) => {
  if (!propertyCode) return false;
  return PRODUCT_SECTIONS.some((section) =>
    productAttributeSections[section.key].some(
      (item) => item.uid !== uid && item.propertyCode === propertyCode,
    ),
  );
};

const createUid = () => `${Date.now()}_${Math.random().toString(16).slice(2)}`;

const createCategoryAttributeRow = () => ({
  uid: createUid(),
  id: '', // 关联关系ID，新增时为空
  attributeCategoryCode: '', // 属性类别（第一级）
  propertyCode: '', // 属性名称（第二级）
  propertyValueCode: '', // 属性值（第三级）
  propertyCategoryList: [], // 第一级选项列表（属性类别）
  propertyCategoryOptions: [], // 第二级选项列表（属性名称）
  propertyValueOptions: [], // 第三级选项列表（属性值）
});

const createProductAttributeRow = () => ({
  uid: createUid(),
  id: '', // 关联关系ID，新增时为空
  propertyCode: '',
  propertyTypeCode: '',
  typeName: '',
  type: '',
  inputType: '',
  propertyValueCodes: [],
  requiredFlag: '',
  showInName: '',
  useForFilter: '',
  allowSupplierEdit: '',
  showInDetail: '',
  valueHint: '',
  valueOptions: [],
});

const hasLoadedCategoryAttributesFromDetail = ref(false);

const init = async () => {
  pageLoading.value = true;
  try {
    getCurrentUserName();

    // 从路由获取 categoryTypeCode
    formData.categoryTypeCode = route.query.categoryTypeCode || '';

    if (isEditMode.value) {
      await getCategoryDetail();
      hasLoadedCategoryAttributesFromDetail.value = true;
      // 仅在编辑模式下预加载父级分类分页数据；详情模式不需要
      if (
        mode.value === 'edit' &&
        showParentCategoryField.value
      ) {
        await loadParentCategories();
      }
    } else {
      formData.code = '--';
    }
  } catch (error) {
    console.error('初始化失败:', error);
  } finally {
    pageLoading.value = false;
  }
};


// 合并分页数据和选中项，保证编辑模式下选中的值始终出现在第一页 options 中，并对重复数据去重
const mergeParentCategoryOptions = (pageItems) => {
  const map = new Map();
  if (selectedParentCategory.value && selectedParentCategory.value.code) {
    map.set(selectedParentCategory.value.code, selectedParentCategory.value);
  }
  (pageItems || []).forEach((item) => {
    if (item && item.code && !map.has(item.code)) {
      map.set(item.code, item);
    }
  });
  parentCategoryOptions.value = Array.from(map.values());
};

// 分页查询上级分类列表（新增/编辑模式使用）
const fetchParentCategories = async () => {
  if (!showParentCategoryField.value || isViewMode.value) return;
  const currentLevel = Number(formData.level) || DEFAULT_PARENT_QUERY_LEVEL;
  const parentLevel = currentLevel - 1;
  if (parentLevel < 1) {
    parentCategoryOptions.value = [];
    parentCategoryPageTotal.value = 0;
    return;
  }
  parentCategoryLoading.value = true;
  try {
    const params = {
      level: currentLevel,
      pageNo: parentCategoryPageNo.value,
      pageSize: parentCategoryPageSize.value,
      status: 1,
    };
    if (parentCategorySearchKeyword.value) {
      params.search = parentCategorySearchKeyword.value;
    }
    const res = await categoryAPI.getParentCategoryList(params, true);

    // 后端数据结构：
    // {
    //   data: [ row1, row2, ... ],
    //   page: { total, pageNo, pageSize, pageSum },
    //   result: { status, code, msg }
    // }
    const rows = Array.isArray(res?.data) ? res.data : [];
    const pageInfo = res?.page || {};

    // 赋值分页信息
    parentCategoryPageTotal.value = Number(pageInfo.total ?? rows.length ?? 0) || 0;
    if (pageInfo.pageNo != null) {
      parentCategoryPageNo.value = Number(pageInfo.pageNo) || parentCategoryPageNo.value;
    }
    if (pageInfo.pageSize != null) {
      parentCategoryPageSize.value = Number(pageInfo.pageSize) || parentCategoryPageSize.value;
    }

    const pageItems = rows
      .filter((item) => {
        const levelMatched = Number(item.level) === parentLevel;
        if (!levelMatched) return false;
        const rawStatus = item.status;
        if (rawStatus === undefined || rawStatus === null || rawStatus === '') {
          return true;
        }
        const statusNumber = Number(rawStatus);
        return Number.isNaN(statusNumber) ? true : statusNumber === 1;
      })
      .map((item) => ({
        code: item.categoryCode,
        name: item.categoryName,
      }));

    mergeParentCategoryOptions(pageItems);
    hasLoadedParentCategories.value = true;
  } catch (error) {
    console.error('获取上级分类失败:', error);
    parentCategoryOptions.value = [];
    parentCategoryPageTotal.value = 0;
  } finally {
    parentCategoryLoading.value = false;
  }
};

const loadParentCategories = async () => {
  // 仅在新增/编辑模式下加载分页数据；详情模式不再请求列表
  if (isViewMode.value) return;
  parentCategoryPageNo.value = 1;
  parentCategorySearchKeyword.value = '';
  hasLoadedParentCategories.value = false;
  await fetchParentCategories();
};

// 使用详情接口返回的 code/name 直接回显商品属性 & 分类属性，
// 避免在页面初始化阶段串行调用大量联动接口
const loadProductAttributesFromDetail = (itemCategoryPropertyRelationModelList) => {
  if (!Array.isArray(itemCategoryPropertyRelationModelList)) {
    PRODUCT_SECTIONS.forEach((section) => {
      productAttributeSections[section.key] = [];
    });
    categoryAttributes.value = [];
    return;
  }

  // 按类型分组，分别处理不同类型的属性
  const typeGroups = {};
  itemCategoryPropertyRelationModelList.forEach((item) => {
    const typeKey = item.type || item.propertyTypeCode;
    if (!typeGroups[typeKey]) {
      typeGroups[typeKey] = [];
    }
    typeGroups[typeKey].push(item);
  });

  // 处理类型1（物料属性）、2（商品属性）、3（其他展示属性）
  const typeMap = {
    '1': 'material',
    '2': 'goods',
    '3': 'display',
  };

  for (const [typeCode, sectionKey] of Object.entries(typeMap)) {
    const group = typeGroups[typeCode];
    if (group && Array.isArray(group)) {
      productAttributeSections[sectionKey] = group.map((item) => {
        // 解析 extProperty JSON 字符串
        let extPropertyObj = {};
        if (item.extProperty && typeof item.extProperty === 'string') {
          try {
            extPropertyObj = JSON.parse(item.extProperty);
          } catch (e) {
            console.warn('解析extProperty失败:', item.extProperty);
          }
        } else if (item.extProperty && typeof item.extProperty === 'object') {
          extPropertyObj = item.extProperty;
        }

        // 解析属性值列表：后端已返回 code + name 时，直接用于回显
        let propertyValueCodes = [];
        let valueOptions = [];

        // 优先使用 categoryPropertyVOList（标准的 {code,name}[]）
        if (
          Array.isArray(item.categoryPropertyVOList) &&
          item.categoryPropertyVOList.length > 0
        ) {
          // 选中值优先从 propertyValueList（code 数组）读取，否则从 VOList 推导
          if (Array.isArray(item.propertyValueList) && item.propertyValueList.length > 0) {
            propertyValueCodes = item.propertyValueList.map((v) => v.code || v);
          } else {
            propertyValueCodes = item.categoryPropertyVOList.map((v) => v.code || v);
          }

          valueOptions = item.categoryPropertyVOList.map((v) => ({
            label: v.code
              ? `${v.code} - ${v.name}`
              : v.name,
            value: v.code || v.name,
          }));
        } else if (Array.isArray(item.propertyValueList) && item.propertyValueList.length > 0) {
          // 兼容老结构：propertyValueList 直接是 {code,name}[] 或 code[]
          const first = item.propertyValueList[0];
          if (first && typeof first === 'object') {
            propertyValueCodes = item.propertyValueList.map((v) => v.code || v);
            valueOptions = item.propertyValueList.map((v) => ({
              label: v.code
                ? `${v.code} - ${v.name}`
                : v.name,
              value: v.code || v.name,
            }));
          } else {
            // 只有 code，没有 name
            propertyValueCodes = item.propertyValueList.slice();
            valueOptions = item.propertyValueList.map((code) => ({
              label: String(code),
              value: code,
            }));
          }
        } else if (item.propertyValueCode && typeof item.propertyValueCode === 'string') {
          try {
            const parsed = JSON.parse(item.propertyValueCode);
            const arr = Array.isArray(parsed) ? parsed : [];
            propertyValueCodes = arr.map((v) => v.code || v);
            valueOptions = arr.map((v) => ({
              label: v.code
                ? `${v.code} - ${v.name}`
                : v.name,
              value: v.code || v.name,
            }));
          } catch (e) {
            // 退化为仅 code 列表
            propertyValueCodes = [item.propertyValueCode];
            valueOptions = [
              {
                label: String(item.propertyValueCode),
                value: item.propertyValueCode,
              },
            ];
          }
        }

          return {
            uid: createUid(),
            id: item.categoryPropertyId || '', // 保存关联关系ID，用于删除
            propertyCode: item.propertyCode || '',
            propertyName: item.propertyName || '',
            propertyTypeCode: item.propertyTypeCode || '',
            typeName: item.typeName || '',
            type: item.type || typeCode,
            inputType: extPropertyObj.inputType || '1', // 1=选择，2=输入
            propertyValueCodes,
            requiredFlag: extPropertyObj.inputStatus === '1' ? '1' : '0',
            showInName: extPropertyObj.skuNameShowStatus === '1' ? '1' : '0',
            useForFilter: extPropertyObj.egoFilterStatus === '1' ? '1' : '0',
            allowSupplierEdit: extPropertyObj.supplierChangeStatus === '1' ? '1' : '0',
            showInDetail: extPropertyObj.skuDetailShowStatus === '1' ? '1' : '0',
            valueHint: extPropertyObj.inputTips || '',
            valueOptions,
          };
      });
    } else {
      productAttributeSections[sectionKey] = [];
    }
  }

  // 处理类型4（分类属性）
  if (typeGroups['4'] && Array.isArray(typeGroups['4'])) {
    const items = typeGroups['4'];
    categoryAttributes.value = items.map((item) => {
      // 解析属性值：从 propertyValueList / categoryPropertyVOList / propertyValueCode 中获取
      let propertyValueCode = '';
      let propertyValueOptions = [];

      // 优先使用 categoryPropertyVOList（标准的 {code,name}[]）
      if (
        Array.isArray(item.categoryPropertyVOList) &&
        item.categoryPropertyVOList.length > 0
      ) {
        const first = item.categoryPropertyVOList[0];
        propertyValueCode = first.code || '';
        propertyValueOptions = item.categoryPropertyVOList.map((v) => ({
          label: v.code
            ? `${v.code} - ${v.name}`
            : v.name,
          value: v.code || v.name,
        }));
      } else if (Array.isArray(item.propertyValueList) && item.propertyValueList.length > 0) {
        const first = item.propertyValueList[0];
        if (first && typeof first === 'object') {
          propertyValueCode = first.code || '';
          propertyValueOptions = item.propertyValueList.map((v) => ({
            label: v.code
              ? `${v.code} - ${v.name}`
              : v.name,
            value: v.code || v.name,
          }));
        } else {
          // 只有 code，没有 name
          propertyValueCode = first;
          propertyValueOptions = item.propertyValueList.map((code) => ({
            label: String(code),
            value: code,
          }));
        }
      } else if (item.propertyValueCode && typeof item.propertyValueCode === 'string') {
        try {
          const parsed = JSON.parse(item.propertyValueCode);
          const arr = Array.isArray(parsed) ? parsed : [];
          if (arr.length > 0) {
            propertyValueCode = arr[0].code || arr[0];
          }
          propertyValueOptions = arr.map((v) => ({
            label: v.code
              ? `${v.code} - ${v.name}`
              : v.name,
            value: v.code || v.name,
          }));
        } catch (e) {
          propertyValueCode = item.propertyValueCode;
          propertyValueOptions = [
            {
              label: String(item.propertyValueCode),
              value: item.propertyValueCode,
            },
          ];
        }
      }

      return {
        uid: createUid(),
        id: item.categoryPropertyId || '', // 保存关联关系ID，用于删除
        attributeCategoryCode: item.propertyTypeCode || '',
        propertyCode: item.propertyCode || '',
        propertyValueCode,
        // 使用详情中的名称，先放入 options 中用于回显；后续用户编辑时再按需加载完整列表
        propertyCategoryList: item.propertyTypeCode
          ? [
              {
                code: item.propertyTypeCode,
                name: item.propertyTypeName || '',
              },
            ]
          : [],
        propertyCategoryOptions: item.propertyCode
          ? [
              {
                code: item.propertyCode,
                name: item.propertyName || '',
              },
            ]
          : [],
        propertyValueOptions,
      };
    });
  } else {
    categoryAttributes.value = [];
  }
};

// 合并 options：以 value 为 key，后端返回的完整列表优先，保留原先用于回显的选中项
const mergeOptionsByValue = (oldList = [], newList = []) => {
  const map = new Map();
  (newList || []).forEach((opt) => {
    if (opt && opt.value !== undefined && opt.value !== null) {
      map.set(opt.value, opt);
    }
  });
  (oldList || []).forEach((opt) => {
    if (opt && opt.value !== undefined && opt.value !== null && !map.has(opt.value)) {
      map.set(opt.value, opt);
    }
  });
  return Array.from(map.values());
};

// 合并 options：以 code 为 key（用于属性类别/属性名称列表）
const mergeOptionsByCode = (oldList = [], newList = []) => {
  const map = new Map();
  (newList || []).forEach((opt) => {
    if (opt && opt.code) {
      map.set(opt.code, opt);
    }
  });
  (oldList || []).forEach((opt) => {
    if (opt && opt.code && !map.has(opt.code)) {
      map.set(opt.code, opt);
    }
  });
  return Array.from(map.values());
};

// 详情加载完成后，后台异步为所有已选属性补全完整属性值列表
const preloadPropertyValueOptions = async () => {
  if (isViewMode.value) return;

  const codesSet = new Set();

  // 商品属性三块
  PRODUCT_SECTIONS.forEach((section) => {
    (productAttributeSections[section.key] || []).forEach((row) => {
      if (row.propertyCode) codesSet.add(row.propertyCode);
    });
  });

  // 分类属性
  (categoryAttributes.value || []).forEach((row) => {
    if (row.propertyCode) codesSet.add(row.propertyCode);
  });

  const uniqueCodes = Array.from(codesSet);
  if (!uniqueCodes.length) return;

  // 并发拉取每个属性的完整属性值列表
  await Promise.all(
    uniqueCodes.map(async (code) => {
      try {
        const options = await getPropertyValuesByCode(code);
        if (!options || !options.length) return;

        // 填充到商品属性
        PRODUCT_SECTIONS.forEach((section) => {
          (productAttributeSections[section.key] || []).forEach((row) => {
            if (row.propertyCode === code) {
              row.valueOptions = mergeOptionsByValue(row.valueOptions, options);
            }
          });
        });

        // 填充到分类属性
        (categoryAttributes.value || []).forEach((row) => {
          if (row.propertyCode === code) {
            row.propertyValueOptions = mergeOptionsByValue(
              row.propertyValueOptions,
              options,
            );
          }
        });
      } catch (e) {
        console.warn('预加载属性值列表失败:', code, e);
      }
    }),
  );
};

// 详情加载完成后，后台异步为分类属性补全「属性类别 / 属性名称」下拉选项
const preloadCategoryAttributeOptions = async () => {
  // 仅编辑模式需要补全分类属性下拉；详情模式只用详情数据回显即可
  if (isViewMode.value) return;
  if (!formData.level) return;
  if (!categoryAttributes.value.length) return;

  try {
    // 1）加载当前 level 下的所有属性类别列表，填充到每一行的 propertyCategoryList
    const categories = await getPropertyCategoriesByType(formData.level);
    if (categories && categories.length) {
      categoryAttributes.value.forEach((row) => {
        if (!row.propertyCategoryList || !row.propertyCategoryList.length) {
          row.propertyCategoryList = categories;
        } else {
          row.propertyCategoryList = mergeOptionsByCode(row.propertyCategoryList, categories);
        }
      });
    }

    // 2）按属性类别（attributeCategoryCode）分组，预加载属性名称列表
    const categoryCodes = Array.from(
      new Set(
        categoryAttributes.value
          .map((row) => row.attributeCategoryCode)
          .filter(Boolean),
      ),
    );

    await Promise.all(
      categoryCodes.map(async (code) => {
        try {
          const options = await getPropertyNamesByCategory(formData.level, code);
          if (!options || !options.length) return;

          categoryAttributes.value.forEach((row) => {
            if (row.attributeCategoryCode === code) {
              row.propertyCategoryOptions = mergeOptionsByCode(
                row.propertyCategoryOptions,
                options,
              );
            }
          });
        } catch (e) {
          console.warn('预加载分类属性名称列表失败:', code, e);
        }
      }),
    );
  } catch (e) {
    console.warn('预加载分类属性选项失败:', e);
  }
};

const getCategoryDetail = async () => {
  const code = route.query.code;
  if (!code) return;
  try {
    const res = await categoryAPI.getCategoryDetail(code, true);
    const detail = res.data || {};

    // 详情模式下，申请日期展示为后端返回的更新时间（仅年月日）
    detailUpdateTime.value = detail.updateTime || '';

    formData.code = detail.categoryCode || '--';
    formData.categoryId = detail.categoryId || ''; // 保存分类主键ID
    formData.level = detail.level ? String(detail.level) : '';
    formData.parentCategoryCode = detail.parentCategoryCode || '';
    formData.categoryName = detail.categoryName || '';

    // 回显上级分类选中项（详情/编辑通用），并保证选中项存在于 options 中
    if (detail.parentCategoryCode && detail.parentCategoryName) {
      selectedParentCategory.value = {
        code: detail.parentCategoryCode,
        name: detail.parentCategoryName,
      };
      mergeParentCategoryOptions([]);
    }

    // 先使用详情数据渲染商品属性与分类属性，避免被联动接口阻塞
    loadProductAttributesFromDetail(detail.categoryPropertyList);

    // 编辑模式下，后台异步：
    // 1）为分类属性补全属性类别/属性名称下拉；
    // 2）为所有已有属性补全完整属性值列表（不阻塞首屏）；
    // 3）如果是品类，再加载商品属性名称列表供后续编辑使用。
    if (!isViewMode.value) {
      preloadCategoryAttributeOptions();
      preloadPropertyValueOptions();
      if (formData.level === '3') {
        getProductPropertyOptions();
      }
    }
  } catch (error) {
    console.error('获取分类详情失败:', error);
  }
};

const getCurrentUserName = () => {
  try {
    const info = userStore.userInfo;
    if (info && info.firstName) {
      currentUser.value = info.firstName;
    } else {
      currentUser.value = '系统用户';
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    currentUser.value = '系统用户';
  }
};

watch(
  () => formData.level,
  async (val, oldVal) => {
    // 详情模式下不做任何联动或清空操作，也不发额外请求
    if (isViewMode.value) return;

    // 初始化阶段：当通过 getCategoryDetail 首次填充 formData.level 时，
    // 不要因为 oldVal 为空就清空已经根据详情组装好的分类属性，
    // 只有用户后续手动修改类型时才触发联动逻辑。
    if (!hasLoadedCategoryAttributesFromDetail.value) return;

    if (!val) {
      formData.parentCategoryCode = '';
      clearParentCategoryValidation();
      // 清空分类属性
      categoryAttributes.value = [];
      // 清空商品属性
      PRODUCT_SECTIONS.forEach((section) => {
        productAttributeSections[section.key] = [];
      });
      productPropertyOptions.value = [];
      return;
    }

    if (val === '1') {
      formData.parentCategoryCode = '';
      parentCategoryOptions.value = [];
      clearParentCategoryValidation();
    } else if (val !== oldVal) {
      await loadParentCategories();
    }

    // 当切换为品类时，加载商品属性列表（仅编辑模式需要）
    if (val === '3') {
      await getProductPropertyOptions();
    } else {
      // 非品类时清空商品属性
      PRODUCT_SECTIONS.forEach((section) => {
        productAttributeSections[section.key] = [];
      });
      productPropertyOptions.value = [];
    }

    // 当类型切换时，重新加载所有分类属性行的属性类别选项
    if (val !== oldVal && categoryAttributes.value.length > 0) {
      const categories = await getPropertyCategoriesByType(val);
      categoryAttributes.value.forEach((row) => {
        // 清空当前选择
        row.attributeCategoryCode = '';
        row.propertyCode = '';
        row.propertyValueCode = '';
        row.propertyCategoryOptions = [];
        row.propertyValueOptions = [];
        // 重新加载属性类别列表
        row.propertyCategoryList = categories;
      });
    }
  }
);

// 监听上级分类 code 变化，同步选中项到 selectedParentCategory，保证提交时有名称
watch(
  () => formData.parentCategoryCode,
  (val) => {
    if (!val) {
      // 清空时不覆盖编辑模式下从详情带过来的 selectedParentCategory
      return;
    }
    const hit = parentCategoryOptions.value.find((item) => item.code === val);
    if (hit) {
      selectedParentCategory.value = hit;
    }
  }
);

// el-select 远程搜索：上级分类（防抖处理，避免高频请求）
const handleParentCategoryRemoteSearchInner = (query) => {
  parentCategorySearchKeyword.value = query || '';
  parentCategoryPageNo.value = 1;
  fetchParentCategories();
};

const handleParentCategoryRemoteSearch = commonJs.debounce(
  handleParentCategoryRemoteSearchInner,
  500,
  false,
);



// el-select 下拉框显示/隐藏时触发
const handleParentCategoryVisibleChange = (visible) => {
  if (visible && !isViewMode.value && !hasLoadedParentCategories.value) {
    // 首次展开时加载第一页数据
    loadParentCategories();
  }
};

// 分页组件 - 修改每页数量
const handleParentCategorySizeChange = (size) => {
  parentCategoryPageSize.value = size;
  parentCategoryPageNo.value = 1;
  fetchParentCategories();
};

// 分页组件 - 切换页码
const handleParentCategoryPageChange = (page) => {
  parentCategoryPageNo.value = page;
  fetchParentCategories();
};

onMounted(() => {
  init();
});
</script>

<style lang="less" scoped>
.form_title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e5e5e5;
}

.form_row {
  margin-bottom: 16px;
}

.form_item {
  display: flex;
  align-items: center;
  height: 32px;
}

.form_label {
  display: inline-block;
  width: 80px;
  text-align: right;
  margin-right: 10px;
  color: #606266;
  font-size: 14px;
}

.form_value {
  color: #303133;
  font-size: 14px;
}

.table-scroll {
  max-height: 500px;
  overflow-y: auto;
}

.select-option-code {
  display: inline-block;
  width: 120px;
  color: #606266;
}

.select-option-name {
  display: inline-block;
  width: calc(100% - 120px);
  color: #303133;
  text-align: right;
}

.section_header {
  display: flex;
  align-items: center;
  column-gap: 20px;
  margin-bottom: 16px;
}

.sub_section_header {
  margin-top: 8px;
}

.sub_title {
  font-size: 14px;
  font-weight: bold;
}

.product_section + .product_section {
  margin-top: 24px;
}

.align-right {
  text-align: right;
}

/deep/ .el-table th {
  background-color: #e5e5e5 !important;
}
/* 详情禁用态保持正常文字颜色 */
/deep/ .el-input.is-disabled .el-input__inner,
/deep/ .el-textarea__inner[disabled] {
  color: #303133 !important;
  -webkit-text-fill-color: #303133 !important;
}
</style>
